<?php

namespace App\Services;


use App\Models\BalanceRecord;
use App\Services\ThirdAPI\GameApiService;
use Illuminate\Support\Facades\Log;


class BalanceRecordService extends BaseService
{
    /**
     * 记录昨天余额
     */
    public static function record()
    {
        $today = date('Y-m-d');
        //计算主钱包
        $sql = "SELECT SQL_CALC_FOUND_ROWS sum(balance) as balance_total, sum(freeze_withdraw) as freeze_total FROM `funds` WHERE `status` = 'enabled'";
        $fundsCount = DB::select($sql)->first();
        $total = $fundsCount['balance_total'] + $fundsCount['freeze_total'];
        //计算子钱包
        $sql = "SELECT SQL_CALC_FOUND_ROWS SUM(balance) AS total, `name`, game_type FROM `funds_child`  WHERE (`status` = 'enabled') GROUP BY game_type";
        $childCount = DB::select($sql);

        $sql = "SELECT id,`name` FROM `partner`";
        $gamesList = DB::select($sql);
        $gamesList = is_array($gamesList) && !empty($gamesList)? array_column($gamesList, 'name', 'id') : [];
        //判断是否使用了共享钱包，使用了则不显示该子钱包
        foreach ($gamesList as $key => $val) {
            $res = GameApiService::getTingGameConfig($val);
            if (isset($res['useSharedwallet']) && $res['useSharedwallet'] == 'true') {
                unset($gamesList[$key]);
            }
        }

        foreach ($childCount as $child) {
            if (in_array($child['game_type'], $gamesList)) {
                $total += $child['total'];
            }
        }

        
        $br = BalanceRecord::where(['date' => $today])->first();
        if (empty($br)) {
            $br = new BalanceRecord();
        }

        $br->date = $today;
        $br->balance = $total;
        $br->freeze_withdraw = $fundsCount['freeze_total'] ?? 0;
        $br->updated = date('Y-m-d H:i:s');
        if (!$br->save()) {
            Log::info('[balance_record] Failed!');
        } else {
            Log::info('[balance_record] insert ok');
        }
    }
}
